const GameModel = require('./../model/GameModel');
let Gcommon = require('./../model/Common');

cc.Class({
  extends: cc.Component,

  properties: {
    gameView: require('GameView'),
    // ball: require('Ball'),
    paddle: require('Paddle'),
    brickLayout: require('BrickLayout'),
    ball_NPC_Prefab: cc.Prefab,
    ball_NPC_Layout: cc.Node,
    audioBall1: {
      type: cc.AudioClip,
      default: null
    },
    audioBlock: {
      type: cc.AudioClip,
      default: null
    },
    audioBuff1: {
      type: cc.AudioClip,
      default: null
    },
    audioPadding: {
      type: cc.AudioClip,
      default: null
    },
    dig_ui: {
      type: cc.Prefab,
      default: null
    },
    GameOverPopue: {
      type: cc.Prefab,
      default: null
    }
  },

  // use this for initialization
  onLoad: function() {
    //安卓返回键退出
    // cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, event => {
    //   if (event.keyCode === cc.KEY.back) {
    //     cc.director.end();
    //   }
    // });
    // this.physicsManager = cc.director.getPhysicsManager();
    this.gameModel = new GameModel();
    this.startGame();
  },

  init() {
    cc.director.getPhysicsManager().enabled = true;
    this.gameModel.init();
    // this.ball.init(this);
    this.gameView.init(this);
    this.paddle.init(this);
    this.brickLayout.init(this.gameModel.bricksNumber);
    // this.overPanel.init(this);

    this.onAddBallNFC(1);
  },

  startGame() {
    this.init();
  },

  onPause() {
    var _directorGame = cc.director.getPhysicsManager();
    var dig_ui = cc.instantiate(this.dig_ui);
    _directorGame.enabled = false;

    this.node.addChild(dig_ui);
    dig_ui.getComponent('popue_dig').show_dlg({
      hide: () => {
        _directorGame.enabled = true;
      },
      restart: () => {
        this.init();
      }
    });
  },

  // resumeGame() {
  // this.overPanel.node.active = false;
  // this.physicsManager.enabled = true;
  // },

  // // pauseOrResumeGame() {
  // //   //暂停或者开始游戏
  // //   if (!this.overPanel.node.active) {
  // //     this.physicsManager.enabled = !this.physicsManager.enabled;
  // //     if (!this.physicsManager.enabled) {
  // //       this.overPanel.show(
  // //         this.gameModel.score,
  // //         this.gameModel.bricksNumber === 0,
  // //         1
  // //       );
  // //     }
  // //   } else {
  // //     // this.overPanel.node.active = false;
  // //     // this.physicsManager.enabled = true;
  // //   }
  // // },

  gameOver() {
    //游戏结束
    // this.physicsManager.enabled = false;
    // this.overPanel.show(
    //   this.gameModel.score,
    //   this.gameModel.bricksNumber === 0
    // );
    this.gameModel.isGame = false;
    let GameOverPopue = cc.instantiate(this.GameOverPopue);
    this.node.addChild(GameOverPopue);
    GameOverPopue.getComponent('game_over_dig').show_dlg({
      restart: () => {
        this.init();
      },
      goHome: () => {
        cc.director.loadScene('home');
      },
      score: this.gameModel.score
    });

    //存储最高分
    if (cc.sys.platform === cc.sys.WECHAT_GAME) {
      let score = this.gameModel.score;

      let openDataContext = wx.getOpenDataContext();
      openDataContext.postMessage({
        score: score,
        type: 'updateMaxScore'
      });
      // let kvScore = { key: 'score', value: score };
      // wx.setUserCloudStroage({
      //   KVDataList: [kvScore],
      //   success: function() {
      //     // 让子域更新当前用户的最高分，因为主域无法得到getUserCloadStorage;
      //     let openDataContext = wx.getOpenDataContext();
      //     openDataContext.postMessage({
      //       score: score,
      //       type: 'updateMaxScore'
      //     });
      //   }
      // });
    }
  },

  // 球碰到砖块
  onBallContactBrick(ballNode, brickNode) {
    if (brickNode.brick_type != 0) {
      // if (this.gameModel.bricksNumber <= 0) {
      //   this.gameOver();
      // }
      this.onBuffbom(brickNode);
      return;
    }
    // console.log('待添加砖头实例的状态');
    this.playSound(this.audioBlock);
    this.gameModel.addScore(10);
    this.gameModel.minusBrick(1);
    this.gameView.updateScore(this.gameModel.score);

    let brickNodeHP = brickNode.children[1].getComponent(cc.Label).string;
    let bombAni = brickNode.children[0].getComponent(cc.Animation);

    if (brickNodeHP <= 1) {
      // 生命值小于1的时候执行动画并销毁最后判断是否结束游戏
      bombAni.play('brick_burst');
      bombAni.on(
        'stop',
        function() {
          brickNode.destroy(); // 前者是官方推荐方法 brickNode.parent = null;
          // if (this.gameModel.bricksNumber <= 0) {
          //   this.gameOver();
          // }
        },
        this
      );
    } else {
      brickNode.children[1].getComponent(cc.Label).string = brickNodeHP -= 1;
    }
  },

  // buff 掉落
  onBuffbom(item) {
    this.playSound(this.audioBuff1);

    var moveto = cc.moveTo(
      2,
      cc.v2(item.getPosition().x, -this.node.height + 600)
    );
    var finish = cc.callFunc(function() {
      item.destroy();
    }, item);
    var myAction = cc.sequence(moveto, finish);
    item.runAction(myAction);
  },

  onBallContactGround(ballNode, groundNode) {
    // 添加逻辑，判断是否是最后一个nfc如果是最后一个则游戏结束，否则则仅销毁小球
    console.log('触摸到底部的判断', this.ball_NPC_Layout);
    if (this.ball_NPC_Layout.childrenCount <= 1) {
      this.gameOver();
    }
    ballNode.destroy();
  },

  onBallContactPaddle(ballNode, paddleNode) {
    this.playSound(this.audioPadding);
  },

  onBallContactWall(ballNode, brickNode) {
    this.playSound(this.audioBall1);
  },

  onDestroy() {
    // this.physicsManager.enabled = false;
  },

  playSound(music) {
    // 游戏音效
    if (Gcommon.musicEffect) {
      cc.audioEngine.playEffect(music, false);
    }
  },

  // buff function

  // add ball NFC type{ num } 类型, 1初始化原始类型 2buff加成nfc
  onAddBallNFC(type) {
    if (type === 1) {
      this.ball_NPC_Layout.removeAllChildren();
    }

    let ball_NPC = cc.instantiate(this.ball_NPC_Prefab);
    ball_NPC.parent = this.ball_NPC_Layout;

    ball_NPC.getComponent('Ball').init(this);
  },

  test() {
    cc.director.loadScene('home');
  }
});
